const https = require("https");
const request = (url,method ='get',option ={}) => {
    return new Promise((resolve) => {
        const options = {
            method: method,  
            headers:{},
            ...option,
        }
         var content = ''
        if(method==='post'){
             content = qs.stringify(option.data); 
            delete options.data
            options.headers['Content-Type'] = 'application/json'
            options.headers['Content-Length'] = content.length
        }   
        var rawData = '';
       const req = https.request(url,options,() => {
            if (res.statusCode == 200) {
                res.on('data', (chunk) => { //接收流数据
                    rawData += chunk;
                });
                res.on('end', () => { //数据接收完毕
                    // 发送从远程服务器获取的响应数据
                    resolve(JSON.parse(rawData))
                });
            }
            
        }).on('error',(err) => {
            resolve(err)
        })
        if(method==='post'){
            req.write(content)
        }
        req.end()
    })
  
}

module.exports = request